package com.hbnu.controller;

import com.hbnu.pojo.DormBuild;
import com.hbnu.pojo.PageModel;
import com.hbnu.pojo.User;
import com.hbnu.service.DormManagerService;
import com.hbnu.service.UserService;
import com.hbnu.service.impl.DormManagerServiceImpl;
import com.hbnu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/student.action")
public class StudentServlet extends HttpServlet {

    DormManagerService dormManagerService = new DormManagerServiceImpl();
    UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决传递过来的中文乱码问题
        req.setCharacterEncoding("utf-8");
        String action = req.getParameter("action");
        //获取学生ID
        String id = req.getParameter("id");
        String disabled = req.getParameter("disabled");

        //获取当前登录的用户
        User user = (User) req.getSession().getAttribute("session_user");
        Integer roleId = user.getRoleId();

        List<DormBuild> builds = new ArrayList<DormBuild>();
        if (roleId.equals(0)) {
            // 如当前用户是超级管理员，他能将学生添加到所有的宿舍楼,查询所有宿舍楼
            builds = dormManagerService.findAll();
        } else if (roleId.equals(1)) {
            //如当前用户 为宿舍管理员，他只能添加学生到其管理的宿舍楼
            builds = dormManagerService.findByUserId(user.getId());
        }
        req.setAttribute("builds", builds);

        if (action != null && "list".equals(action)) {
            //查询学生在右侧展示
            String dormBuildId = req.getParameter("dormBuildId");
            String searchType = req.getParameter("searchType");
            String keyword = req.getParameter("keyword");
            // 当前要查询的页面
            String pageIndex = req.getParameter("pageIndex");

            // 默认查询第一页，需两个参数，当前页码pageIndex，每页展示的条数
            PageModel pageModel = new PageModel();
            if (pageIndex != null && !pageIndex.equals("")) {
                pageModel.setPageIndex(Integer.parseInt(pageIndex));
            }
            List<User> students = userService.findStudent(dormBuildId, searchType, keyword, user, pageModel);

            // 获取查询处理的总数量
            Integer totalNum = userService.findTotalNum(dormBuildId, searchType, keyword, user);

            req.setAttribute("totalNum", totalNum);
            req.setAttribute("pageIndex", pageIndex);
            req.setAttribute("dormBuildId", dormBuildId);
            req.setAttribute("searchType", searchType);
            req.setAttribute("keyword", keyword);
            req.setAttribute("students", students);
            req.setAttribute("mainRight", "/jsp/studentList.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        } else if (action != null & action.equals("preAdd")) {
// 根据用户角色查询宿舍楼进行添加学生，
// 如当前用户 为宿舍管理员，他只能添加学生到其管理的宿舍楼
// 跳转到学生的添加页面
            req.setAttribute("mainRight", "/jsp/studentAddOrUpdate.jsp");
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        } else if (action.equals("save")) {
            // 保存学生
            String stuCode = req.getParameter("stuCode");
            String name = req.getParameter("name");
            String sex = req.getParameter("sex");
            String tel = req.getParameter("tel");
            String password = req.getParameter("passWord");
            String dormBuildId = req.getParameter("dormBuildId");
            String dormCode = req.getParameter("dormCode");
// 未存在，则保存
            User student = userService.findByStuCode(stuCode);
            if (id != null && !id.equals("")) {
// 更新之前，查询数据库是否已经存在当前学号的学生，如已存在，则跳转到添加页面
                if (student != null &&
                        !student.getId().equals(Integer.parseInt(id))) {
                    // 当前学号的学生已存在，请重新修改，跳转到该学生的修改页面
                    req.getRequestDispatcher("/student.action?action=preUpdate&id=" + id).forward(req, resp);
                    ;
                } else {
// 更新
                    User studentUpdate = userService.findById(Integer.parseInt(id));
                    studentUpdate.setStuCode(stuCode);
                    studentUpdate.setSex(sex);
                    studentUpdate.setTel(tel);
                    studentUpdate.setName(name);
                    studentUpdate.setPassword(password);
                    studentUpdate.setDormBuildId(Integer.parseInt(dormBuildId));
                    studentUpdate.setDormCode(dormCode);
                    studentUpdate.setDisabled(0);
                    User user1 = studentUpdate;
                    userService.updateStudent(user1);
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/student.action?action=list");
                }
            } else {
                // 保存
                if (student != null) {
// 在保存之前，查询数据库是否已经存在当前学号的学生，如已存在，则跳转到添加页面
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/student.action?action=preAdd");


                } else {
                    User user2 = new User();
                    user2.setStuCode(stuCode);
                    user2.setSex(sex);
                    user2.setTel(tel);
                    user2.setName(name);
                    user2.setPassword(password);
                    user2.setDormBuildId(Integer.parseInt(dormBuildId));
                    user2.setDormCode(dormCode);
                    user2.setRoleId(2);
                    user2.setCreateUserId(user.getId());
                    userService.saveStudent(user2);
                    resp.sendRedirect(getServletContext().getContextPath() +
                            "/student.action?action=list");
                }
            }
        } else if (action != null & action.equals("preUpdate")) {
// 通过学生id查找学生并保存，以便在页面展示
            User userUpdate = userService.findById(Integer.parseInt(id));
// 判断当前登录的用户是否有修改该学生的权限，如没有跳转到学生管理的列表页；如有则跳转到修改页面
            User user2 = userService.findByUserIdAndManager(userUpdate.getId(),
                    user);
            if (user2 != null) {
// 表示有修改权限
                req.setAttribute("userUpdate", userUpdate);
// 跳转到学生管理的修改页面
                req.setAttribute("mainRight", "/jsp/studentAddOrUpdate.jsp");
                req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
            } else {
// 表示无修改权限，跳转到学生管理的列表页
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/student.action?action=list");
            }
        }else if (action != null & action.equals("deleteOrActive")) {
// 删除或激活
            User studentUpdate = userService.findById(Integer.parseInt(id));
            studentUpdate.setDisabled(Integer.parseInt(disabled));
            // 判断当前登录的用户是否有修改该学生的权限，如没有跳转到学生管理的列表页；如有则跳转到修改页面
            User user2 = userService.findByUserIdAndManager(studentUpdate.getId(),
                    user);
            if (user2 != null) {
                // 表示有修改权限
                userService.updateStudent(studentUpdate);
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/student.action?action=list");
            } else {
// 表示无修改权限，跳转到学生管理的列表页
                resp.sendRedirect(getServletContext().getContextPath() +
                        "/student.action?action=list");
            }
        }
    }
}
